--[[
	暂时不知道什么用
]]
local timetool = require "timetool"
local configdao = require "configdao"
local skynet = require "skynet"
local filelog = require "filelog"
local json = require "cjson"
local base = require "base"
local table = table
local type = type
json.encode_sparse_array(true,1,1)

--[[
	使用说明:

	在需要使用到的服务的main中加入如下代码：
    --加载mq服务
    local recordmqsvrs = configdao.get_cfgsvrs("recordmqsvrs")
    if recordmqsvrs ~= nil then
        for svr_id, conf in pairs(recordmqsvrs) do
            local svr = skynet.newservice("redisdb", svr_id)
            skynet.call(svr, "lua", "init", conf)
        end
    end

    在config_svr中加入如下配置信息：
    recordmqsvrs = {
	recordmq_1={
		host="127.0.0.1",
		port=6379,
		db=14,
		--auth = "foobared"
		mqname = "record1",
	},

	接口使用方式
	local gamerecords = require "gamerecords"

	local gamerecoard = gamerecords.new()
	
	gamerecord.init(id)                 --id和桌子的战绩唯一表示一至
	gamerecord.insert(cmd, msg, issave) --当issave为true时将会上报信息


}

]]
local function GameRecords(obj)
	obj = obj or {}

	local recordmqsvrs = nil
	local mqsvr_id = nil
	local index = 0

	local function clone(t)
		local target = {}
		for k, v in pairs(t) do
			if type(v) == "table" then
				target[k] = clone(v)
			else
				target[k] = v
			end
		end
		return target
	end

	function obj.insert(cmd, msg, issave)
		local record_ = {
			time = timetool.get_time(),
			cmd = cmd,
			msg = clone(msg),
		}
		table.insert(obj.record, record_)
		if issave then
			local recordstr = obj.serialize()
			if recordmqsvrs == nil then
				recordmqsvrs = configdao.get_cfgsvrs("recordmqsvrs")	
			end
			local tmp = {}
			for svr_id, _ in pairs(recordmqsvrs) do
				table.insert(tmp, svr_id)
			end
			index = base.strtohash(obj.id) % (#tmp) + 1
			mqsvr_id = tmp[index]  
			--发送到MQ
			skynet.send(mqsvr_id, "lua", "lpush", false, recordmqsvrs[mqsvr_id].mqname, recordstr)
		end
	end

	function obj.getid()
		return obj.id
	end

	function obj.serialize()
		return json.encode({id=obj.id, record=obj.record})
	end

	function obj.init(id)
		obj.record = {}
		obj.id = id
	end
	return obj
end

local function new(...)
	return GameRecords(...)
end

return {new=new}